package com.xrit.sunnyday.controller;

import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.exception.SunnydayException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;

import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 * @RestControllerAdvice ：将标有@RestController的类进行"duan duan duan"增强
 */
@RestControllerAdvice
public class HandlerAdvice {
    /**
     * @ExceptionHandler: 异常捕手，捕谁要写清楚，
     * 进了方法就相当于进了catch(SunnydayException){
     *     ...我们要捕获后进行的操作
     * }
     * return:要处理的对象
     */
    @ExceptionHandler(SunnydayException.class)
    public Result handSunnydayException(SunnydayException se){
        return new Result(false,se.getMessage());
    }

    /**
     * 所有未知的异常
     * @param he
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception he){
        he.printStackTrace();
        return new Result(false, "发生未知错误，操作失败，请联系管理员");
    }

    /**
     * 密码错误
     * @param he
     * @return
     */
    @ExceptionHandler(BadCredentialsException.class)
    public Result handBadCredentialsException(BadCredentialsException he){
        return handleUserPassword();
    }

    /**
     * 用户名不存在
     * @param he
     * @return
     */
    @ExceptionHandler(InternalAuthenticationServiceException.class)
    public Result handInternalAuthenticationServiceException(InternalAuthenticationServiceException he){
        return handleUserPassword();
    }


    private Result handleUserPassword(){
        return new Result(false, "用户名或密码错误");
    }

    /**
     * 权限不足
     * @param he
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    public Result handAccessDeniedException(AccessDeniedException he){
        return new Result(false, "没有权限");
    }


}
